package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.List;

/**
 * @author LiangTianQi
 * @describe
 * @date 2020/11/11 22:41
 */
@Service(interfaceClass = OrderSettingService.class)
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    //注入redis数据库连接池
    @Autowired
    private JedisPool jedisPool;

    @Override
    public List<OrderSetting> getOrdersettingByMonth(String date) {
        //查询在某个日期段之间的信息
        //月份日期有30有31不确定，但是数据库查询时，该月份没有31号数据库会查询，只是查不到数据
        String startDate = date + "-1";
        String endDate = date + "-31";
        return orderSettingDao.getOrdersettingByMonth(startDate,endDate);
    }

    /**
     * 添加数据到数据库中
     * @param orderSetting
     */
    @Override
    @Transactional
    public void add(OrderSetting orderSetting) {

        //如果预约的日期重复添加则没有作用，还会影响显示，所以要进行判断
        //判断是否已经存在该日期
        long count=orderSettingDao.getByOrderDate(orderSetting.getOrderDate());
        if (count == 0) {
            //不存在则添加
            orderSettingDao.add(orderSetting);
        }else {
            //存在则修改
            orderSettingDao.editNumberByOrderDate(orderSetting);
        }

    }

    @Override
    public void setNumber(Integer number) {
        //往reids中添加默认人数
        /*Jedis jedis = jedisPool.getResource();
        jedis.set("number", number.toString());*/

        //向数据库中添加数据
        orderSettingDao.setNumber(number);
    }

    @Override
    public void triggerAdd(OrderSetting orderSetting) {
        //从数据库中读取默认的人数
        Integer number=orderSettingDao.getNumber();
        orderSetting.setNumber(number);

        //如果预约的日期重复添加则没有作用，还会影响显示，所以要进行判断
        //判断是否已经存在该日期
        long count=orderSettingDao.getByOrderDate(orderSetting.getOrderDate());
        if (count == 0) {
            //不存在则添加
            orderSettingDao.add(orderSetting);
        }else {
            //存在则修改
            orderSettingDao.editNumberByOrderDate(orderSetting);
        }
    }

    /**
     * 根据前段传来的数据更新定时器任务的执行时间
     * @param number
     */
    @Override
    public void updateCron(String number) {
        String cron = null;
        cron = "0 0 0 " + number + " * ?";
        orderSettingDao.updateCron(cron);
    }

    @Override
    public String getCron() {
        String cron = orderSettingDao.getCron();
        return cron;
    }
}
